package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.query.TravelCondition;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private MongoTemplate template;
    @Autowired
    TravelRepository repository;
    @Autowired
    UserInfoRepository userInfoRepository;
    @Autowired
    IDestinationService destinationService;
    @Override
    public Page<Travel> list(TravelQuery qo) {
        Query query = new Query();
        Long total = template.count(query,Travel.class);
        if(total == 0){
            return Page.empty();
        }
        Pageable of = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(),
                Sort.Direction.ASC,"_id");//此处参数要传够
        query.with(of);
        List<Travel> travels = template.find(query,Travel.class);
        return new PageImpl<>(travels,of,total);
    }


    @Override
    public List<Travel> list() {
        return  repository.findAll();
    }

    @Override
    public String changeState(String id, int state) {
        Travel travel = repository.findById(id).get();
        if (travel != null) {
            if (travel.getState() == 0 || travel.getState() == 3) {
                return "草稿状态无法修改";
            } else {
                travel.setState(state);
                repository.save(travel);
            }
            return "修改成功";
        }
        return "游记不存在";
    }

    @Override
    public Travel getContentById(String id) {
        return repository.findById(id).get();
    }

    @Override
    public Page<Travel> queryByDestId(TravelQuery qo) {
//            List<Travel> travels = repository.findByDestId(query);
        Query query = new Query();
        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        TravelCondition day = qo.getDay();
        TravelCondition perExpend = qo.getPerExpend();
        if(day != null){
            query.addCriteria(Criteria.where("day").gte(day.getMin()).lte(day.getMax()));
        }
        //旅游人均消费
        if(perExpend != null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpend.getMin()).lte(perExpend.getMax()));
        }
        //1: 默认, 按照最新(时间排序)  2:最热-viewnum
        Pageable of;
        if(qo.getOrderType() == 2){
            of = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.DESC, "viewnum");
        }else {
            of = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                    Sort.Direction.DESC, "createTime");
        }
        Long total = template.count(query,Travel.class);
        if(total == 0){
            return Page.empty();
        }
//        List<Travel> travels = template.find(query,Travel.class);
        query.with(of);
        Page<Travel> travels = DBHelper.query(template, Travel.class, query, qo.getPageable());
        for(Travel travel:travels){
            String uid = travel.getUserId();
            travel.setAuthor(userInfoRepository.findById(uid).get());
        }
        return travels;
    }

    @Override
    public Travel findById(String id) {
            UserInfo userInfo = userInfoRepository.findById(repository.findById(id).get().getUserId()).get();
            Travel travel = repository.findById(id).orElse(null);
            travel.setAuthor(userInfo);
        return travel;

    }

    @Override
    public String saveOrUpdate(Travel travel) {
        //1: 目的地名称
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName());
        //3:创建时间/最后更新时间
        travel.setLastUpdateTime(new Date());
        if(!StringUtils.hasLength(travel.getId())){
            //添加
            travel.setId(null);
            //创建时间
            travel.setCreateTime(new Date());

            repository.save(travel);
        }else{
            //更新
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(travel.getId()));

            DBHelper.update(template, query, travel,
                    "destId","destName","title",
                    "coverUrl","travelTime","perExpend",
                    "day","person","lastUpdateTime",
                    "isPublic","state","summary","content");
        }

        return travel.getId();
    }

    @Override
    public List<Travel> getViewnumTop3(String destId) {
        //点击量前3
        Pageable of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        return repository.findByDestId(destId, of);
    }

    @Override
    public List<Travel> findByDestName(String keyword) {
        List<Travel> travels = repository.findByDestName(keyword);
        for(Travel travel:travels){
            System.out.println(userInfoRepository.findById(travel.getUserId()));
            travel.setAuthor(userInfoRepository.findById(travel.getUserId()).get());
//            System.out.println(travel);
        }
        return travels;
    }

    @Override
    public Travel get(String id) {
        return repository.findById(id).get();
    }
}
